package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.myapplication.middleControls.DialogActivity;
import com.example.myapplication.middleControls.PatchActivity;
import com.example.myapplication.middleControls.ShapeActivity;
import com.example.utils.Constants;
import com.example.utils.LooperThread;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //设置全局属性
    private final static String TAG = "MainActivity";
    OkHttpClient okHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        okHttpClient = new OkHttpClient();


        LooperThread looperThread = new LooperThread();//创建一个looper线程
        looperThread.start();//开启线程

        findViewById(R.id.bt_calculator).setOnClickListener(this);//计算器
        findViewById(R.id.bt_glide).setOnClickListener(this);//Glide
        findViewById(R.id.bt_order).setOnClickListener(this);//order
        findViewById(R.id.setting).setOnClickListener(this);//setting
        findViewById(R.id.bt_shape).setOnClickListener(this);//形状图形-Shape
        findViewById(R.id.bnt_report_position).setOnClickListener(this);
        findViewById(R.id.bnt_9patch).setOnClickListener(this);//九宫图
        findViewById(R.id.bnt_alert).setOnClickListener(this);//alert
        findViewById(R.id.bnt_hign).setOnClickListener(this);//高级视图组件


    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt_calculator) {
            Intent intent = new Intent(this, CalculatorActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.bt_glide) {
            Intent intent = new Intent(this, GlideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("send_content", "你好呀，Glide，帮我显示下面的图片好吗");
            bundle.putString("url", "网络");
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (v.getId() == R.id.bt_order) {
            checkToGotoPage();
        } else if (v.getId() == R.id.setting) {
            Intent intent = new Intent(this, SettingActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.bt_shape) {
            Intent intent = new Intent(this, ShapeActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.bnt_report_position) {
            getPosition();
            Log.d(TAG, String.valueOf(Constants.getLng()));
            Log.d(TAG, String.valueOf(Constants.getLat()));
            if (Constants.getLng() != 0 && Constants.getLat() != 0) {
                // 创建提醒对话框的建造器
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                // 设置对话框的标题文本
                builder.setTitle("当前位置");
                // 设置对话框的内容文本
                builder.setMessage("经度：" + String.valueOf(Constants.getLng()) + "\n" + "纬度：" + String.valueOf(Constants.getLat()));
                // 设置对话框的否定按钮文本及其点击监听器
                builder.setNegativeButton("取消", (dialog, which) -> {

                });
                // 设置对话框的肯定按钮文本及其点击监听器
                builder.setPositiveButton("上传位置", (dialog, which) -> {

                });
                // 根据建造器构建提醒对话框对象
                AlertDialog dialog = builder.create();
                // 显示提醒对话框
                dialog.show();
            }

        } else if (v.getId() == R.id.bnt_9patch) {
            Intent intent = new Intent(this, PatchActivity.class);
            startActivity(intent);

        } else if (v.getId() == R.id.bnt_alert) {
            Intent intent = new Intent(this, DialogActivity.class);
            startActivity(intent);

        } else if (v.getId() == R.id.bnt_hign) {
            Intent intent = new Intent(this, HighActivity.class);
            startActivity(intent);
        }


    }

    private void checkToGotoPage() {

    }

    BluetoothHeadset bluetoothHeadset;

    // Get the default adapter
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    private BluetoothProfile.ServiceListener profileListener = new BluetoothProfile.ServiceListener() {
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
            if (profile == BluetoothProfile.HEADSET) {
                bluetoothHeadset = (BluetoothHeadset) proxy;
            }
        }

        public void onServiceDisconnected(int profile) {
            if (profile == BluetoothProfile.HEADSET) {
                bluetoothHeadset = null;
            }
        }
    };


    //发送get同步请求
    public void getSync(View v) {
        new Thread() {
            @Override
            public void run() {
                //默认为get请求
                //创建request请求对象
                Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
                //准备好请求的call对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.d(TAG, "getSync: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //发送get异步请求
    public void getAsync(View v) {
        Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
        //准备好请求的call对象
        Call call = okHttpClient.newCall(request);
        //异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "getAsync: " + response.body().string());
                }
            }
        });

    }

    //发送post同步请求
    public void postSync(View v) {
        new Thread() {
            @Override
            public void run() {
                FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();
                Request request = new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();
                //准备好请求的call对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.d(TAG, "postSync: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //发送post异步请求
    public void postAsync(View v) {
        FormBody formBody = new FormBody.Builder().add("a", "1").add("b", "2").build();
        Request request = new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.d(TAG, "postAsync: " + response.body().string());
                }
            }
        });
    }

    /**
     * 获取经纬度
     */
    public void getPosition() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 102);
            return;
        }
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 位置监听器
        LocationListener locationListener = new LocationListener() {
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }

            public void onLocationChanged(Location location) {
                // 设置经纬度
                if (location != null) {
                    Constants.setLng(location.getLongitude());
                    Constants.setLat(location.getLatitude());
                    // 获取到位置后停止位置更新
                    if (locationManager != null) {
                        locationManager.removeUpdates(this);
                    }
                }
            }
        };
        if (locationManager != null) {
            // 获得最后一次变化的位置
            Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            // 设置经纬度
            if (gpsLocation != null) {
                Constants.setLng(gpsLocation.getLongitude());
                Constants.setLat(gpsLocation.getLatitude());
            } else if (netLocation != null) {
                Constants.setLng(netLocation.getLongitude());
                Constants.setLat(netLocation.getLatitude());
            }
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    // 这行代码需要放在主线程中执行
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                }
            });
        }

    }
}